package org.hcyspartnoc.demo.common.core.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.hcyspartnoc.demo.common.core.annotation.Log;
import org.hcyspartnoc.demo.common.core.context.BaseContextHolder;
import org.hcyspartnoc.demo.pojo.po.system.SysUserPo;
import org.hcyspartnoc.demo.utils.RequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;

@Aspect
@Component
public class GlobalLogAop {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalLogAop.class);

    //任意返回值和参数的controller下的方法
    @Pointcut("execution(* org.hcyspartnoc.*.controller..*.*(..))")
    void allController() {
    }

    @Around("allController()")
    public Object saveLog(ProceedingJoinPoint pjp) {
        MethodSignature ms = (MethodSignature) pjp.getSignature();
        Method method = ms.getMethod();//获取当前方法
        long start = System.currentTimeMillis();
        try {//执行方法
            Object result = pjp.proceed(pjp.getArgs());
            long execTime = System.currentTimeMillis() - start;//总执行耗时
            if (method.isAnnotationPresent(Log.class)) {
                Log log = method.getAnnotation(Log.class);
                SysUserPo currentUser = BaseContextHolder.getContext().getBaseCurrentUser();
                StringBuilder sb = new StringBuilder().append("\n")
                        .append("ip:").append(RequestUtil.getIp()).append(" | ");
                sb.append("用户：").append(currentUser.getId()).append(" | ")
                        .append("角色编号：").append(currentUser.getRoleId()).append(" | ");
                sb.append("访问接口：").append(log.title()).append("\n");
                if (log.isSaveRequestData())
                    sb.append("请求参数：").append(Arrays.toString(pjp.getArgs())).append("\n");
                if (log.isSaveResponseData())
                    sb.append("响应数据：").append(result).append("\n");
                sb.append("执行耗时：").append(execTime).append("ms\n");
                LOGGER.info(sb.toString());
            }

            return result;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}